package com.zjsru.plan2024.oneday;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: cookLee
 * @Date: 2024-01-07
 * 赎金信
 */
public class CanConstruct {
    /**
     * 主
     * \
     * 输入：ransomNote = "a", magazine = "b"
     * 输出：false
     * \
     * 输入：ransomNote = "aa", magazine = "ab"
     * 输出：false
     * \
     * 输入：ransomNote = "aa", magazine = "aab"
     * 输出：true
     * \
     * @param args args
     */
    public static void main(String[] args) {
        CanConstruct canConstruct = new CanConstruct();
        String ransomNote = "aa";
        String magazine = "aab";
        System.out.println(canConstruct.canConstruct2(ransomNote, magazine));
    }

    /**
     * 数组
     *
     * @param ransomNote 赎金票据
     * @param magazine   杂志
     * @return boolean
     */
    public boolean canConstruct(String ransomNote, String magazine) {
        if (ransomNote.length() > magazine.length()) {
            return false;
        }
        int[] magazines = new int[26];
        for(int i = 0; i < magazine.length(); i++){
            char c = magazine.charAt(i);
            magazines[c - 'a']++;
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            char c = ransomNote.charAt(i);
            magazines[c - 'a']--;
            if(magazines[c - 'a'] < 0){
                return false;
            }
        }
        return true;
    }

    /**
     * 哈希表
     *
     * @param ransomNote 赎金票据
     * @param magazine   杂志
     * @return boolean
     */
    public boolean canConstruct2(String ransomNote, String magazine) {
        Map<Character, Integer> constructMap = new HashMap<>();
        for (char c : magazine.toCharArray()) {
            constructMap.put(c, constructMap.getOrDefault(c, 0) + 1);
        }
        for (char c : ransomNote.toCharArray()) {
            if (constructMap.containsKey(c)) {
                Integer value = constructMap.get(c);
                value = value - 1;
                constructMap.put(c, value);
                if (value < 0) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }

}
